﻿using System;
using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.Timeline;
//#if UNITY_EDITOR
//using UnityEditor;
//#endif

public abstract class JumpableTrack : TrackAsset
{
    /// <summary>
    /// 不会执行
    /// </summary>
    /// <param name="clip"></param>
    //protected override void OnCreateClip(TimelineClip clip)
    //{
    //    Debug.Log("OnCreateClip");
    //}

    private void OnEnable()
    {
        //Debug.Log("TrackAsset.OnEnable");

        //Inject();
        JumpabelManager.RegisterDelayInjdectJumpableTrack(this);
        
        //Debug.LogFormat("parent = {0}", parent.name);//Asset文件的名称
        //Debug.LogFormat("timelineAsset = {0}", timelineAsset.name);//Asset文件的名称
    }

    private void OnDestroy()
    {
        Debug.Log("JumpableTrack.OnDestroy");
    }

    //protected override void OnAfterTrackDeserialize()
    //{
    //    Debug.Log("TrackAsset.OnAfterTrackDeserialize");

    //    Inject();
    //}

    public void Inject()
    {
//#if UNITY_EDITOR
//        Debug.LogFormat("EditorApplication.isPlaying = {0}", EditorApplication.isPlaying);
//        //进入到这里时，isPlaying仍然为false
//        if (!EditorApplication.isPlaying)
//        {
//            return;
//        }
//#endif

        //Debug.Log("TrackAsset.Inject");

        foreach (TimelineClip clip in m_Clips)
        {
            PlayableAsset asset = (PlayableAsset)clip.asset;

            Type type = asset.GetType();
            if (typeof(IJumpableAsset).IsAssignableFrom(type))
            {
                IJumpableAsset jumpableAsset = (IJumpableAsset)asset;
                jumpableAsset.OwnerTrack = this;

                TimeInfo timeInfo = new TimeInfo(clip.start, clip.end);
                jumpableAsset.TimeInfo = timeInfo;

                //Debug.LogFormat("IJumpableAsset [{0}] Set : Track [{1}], Clip [{2}~{3}]", asset.GetInstanceID(), GetInstanceID(), clip.start, clip.end);
            }
        }

        //能够获取到
        //foreach (TimelineClip clip in m_Clips)
        //{
        //    PlayableAsset asset = (PlayableAsset)clip.asset;

        //    Type type = asset.GetType();
        //    if (typeof(IJumpableAsset).IsAssignableFrom(type))
        //    {
        //        IJumpableAsset jumpableAsset = (IJumpableAsset)asset;

        //        Debug.LogFormat("IJumpableAsset [{0}] Get Immediately : Track [{1}], [{2}~{3}]",
        //            asset.GetInstanceID(), jumpableAsset.OwnerTrack.GetInstanceID(),
        //            jumpableAsset.TimeInfo.start, jumpableAsset.TimeInfo.end);
        //    }
        //}
    }
}
